<template>
  <el-cascader
    :value="value"
    :options="treeData"
    :props="props"
    size="mini"
    separator="-"
    @change="handleChange"
    @visible-change="visibleChange"
  />
</template>

<script>
import { getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
export default {
  name: 'SelectTree',
  props: {
    value: {
      type: Number, // 存储的是部门的id  3 4 5
      default: null
    }
  },
  data() {
    return {
      treeData: [], // 赋值给 级联组件的options
      props: {
        label: 'name',
        value: 'id'
      }
    }
  },
  created() {
    // 获取数据
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      // 格式化数组
      this.treeData = transListToTreeData(await getDepartment(), 0)
    },
    handleChange(list) {
      // 取到数组的最后一次
      if (list.length > 0) {
        this.$emit('input', list[list.length - 1]) // 将最后一位的id取出来 传出去
      } else {
        this.$emit('input', null) // 如果长度为0 说明值为空
      }
    },
    // 解决组件下拉卡死问题
    visibleChange() {
      this.$nextTick(() => {
        const $el = document.querySelectorAll('.el-cascader-panel .el-cascader-node[aria-owns]')
        Array.from($el).map((item) => item.removeAttribute('aria-owns'))
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
